/**
 * 模态框
 */
module.exports = function($scope, $state, $modalInstance, $resource, roleInfo){
    
    //加载角色已绑定的模板
    $scope.loadTemplete = function () {
        $resource('/api/as/sc/role/getTempleteForRole', {}, {}).save({'role_id': roleInfo.id}, function (res) {
            if (res.errcode === 0) {
                //两边加逗号,方便字符串判断,防止有部分重复内容,出现判断失误
                var temp = ',' + res.data.templete_code + ',';
            }
            init(temp);
        });
    };
    $scope.loadTemplete();
    
    //初始化查询全部模板
    function init(templete_code){
        $resource('/api/ac/tc/ticketSaleTempleteService/getTempleteListForSys', {}, {}).save({}, function (res) {
            if (res.errcode === 0) {
                $scope.templete_list = res.data;
                if(templete_code){
                    angular.forEach($scope.templete_list, function(item){
                        var index = templete_code.indexOf(',' + item.templete_code + ',');
                        if(index != -1){
                            item.sel = true;
                        }
                    });
                }
            } else {
                alert(res.errmsg);
            }
        });
    };

    //选择全部模板
    $scope.selAll = function () {
        angular.forEach($scope.templete_list, function(item){
            item.sel = $scope.all? true : false;
        });
    };

    //确定
    $scope.ok = function () {
        var selected_templete = [];
        angular.forEach($scope.templete_list, function(item){
            if(item.sel){
                selected_templete.push(item.templete_code);
            }
        });
        var para = {
            'role_id' : roleInfo.id,
            'templete_code' : selected_templete.toString()
        }
        $resource('/api/as/sc/role/addTempleteForRole', {}, {}).save(para, function (res) {
            if (res.errcode !== 0) {
                alert(res.errmsg);
            }
            //关闭模态框
            $modalInstance.close();
		});
    };

    //取消
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };


};